const storagePath = './temp/bilibili';
import fetch from 'node-fetch';
import fs from 'fs';
import path from 'path';

export class ExamplePlugin extends plugin {
  constructor() {
    super({
      name: '查bfangled',
      dsc: 'zy-yyds',
      event: 'message',
      priority: -Infinity,
      rule: [
        {
          reg: '^#?向(.*)发弹幕(.*)$',
          fnc: 'cf'
        }
      ]
    });
  }

  async cf(e) {
    // 提取房间号和内容
    const match = e.msg.match(/^#?向(\d+)发弹幕(.*)$/);
    if (!match) {
      e.reply("格式不正确，请使用 #向<房间号>发弹幕<内容>", true);
      return;
    }
    const [_, roomid, msg] = match;

    // 读取用户Cookies
    const cookieFile = path.join(storagePath, 'user_cookies.json');
    let cookies = {};
    try {
      cookies = JSON.parse(fs.readFileSync(cookieFile, 'utf8'));
    } catch (err) {
      logger.error("无法读取cookie文件:", err);
      e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
      return;
    }

    const userCookies = cookies[e.user_id];
    if (!userCookies || !userCookies.SESSDATA) {
      logger.warn(`User ${e.user_id} does not have valid cookies.`);
      e.reply("未能绑定cookie，请发送b站扫码登录进行绑定", true);
      return;
    }
    const access_token = userCookies.access_token
    const sessdata = userCookies.SESSDATA;
    const csrf = userCookies.csrf;
    const DedeUserID = userCookies.DedeUserID;
    const DedeUserID__ckMd5 = userCookies.DedeUserID__ckMd5;
    const sid = userCookies.sid;
    // 构造API请求
    const url = 'https://api.live.bilibili.com/msg/send';
    const headers = {
      'referer': 'https://www.bilibili.com/',
      'Cookie': `access_token=${access_token}; SESSDATA=${sessdata}; csrf=${csrf}; DedeUserID=${DedeUserID}; DedeUserID__ckMd5=${DedeUserID__ckMd5}; sid=${sid}`,
      'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3',
      'Content-Type': 'application/x-www-form-urlencoded'
    };
    const postData = new URLSearchParams({
      color: 16777215,
      fontsize: 25,
      mode: 1,
      msg: msg.trim(),
      rnd: Math.floor(Date.now() / 1000),
      roomid: roomid,
      bubble: 0,
      csrf_token: csrf,
      csrf: csrf
    });

    try {
      const response = await fetch(url, {
        method: 'POST',
        headers,
        body: postData
      });

      const result = await response.json();
      if (result.code === 0) {
        logger.mark(`${e.user_id} 向 ${roomid} 直播间发送弹幕成功: ${msg}`);
        e.reply("弹幕发送成功！", true);
      } else {
        logger.error(`发送失败 ${roomid}: ${result.message || result.msg}`);
        e.reply(`弹幕发送失败: ${result.message || result.msg || result.code}`, true);
      }
    } catch (error) {
      logger.error("发送请求时出错:", error);
      e.reply("发送弹幕时发生了错误，请稍后再试。", true);
    }
  }
}